package com.verlet.servicehi;

import com.rabbitmq.client.Channel;
import com.verlet.servicehi.entity.MessageObject;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author verlet
 * @date 2020/2/5
 */
@Component
public class RabbitReceiver {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "test001.topic.queue", durable = "false"),
            exchange = @Exchange(value = "test001.topic.exchange", durable = "false", type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true"),
            key = "test001.#"))
    @RabbitHandler
    public void onMessage(Message<String> message, Channel channel) throws IOException {
        System.out.println(message.getPayload());
        System.out.println(message.getHeaders());
        channel.basicAck((long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG), false);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "test001.topic.queue1", durable = "false"),
            exchange = @Exchange(value = "test001.topic.exchange1", durable = "false", type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true"),
            key = "test002.#"))
    @RabbitHandler
    public void onMessage2(@Payload MessageObject messageObject, Channel channel, @Headers Map<String, Object> headers) throws IOException {
        System.out.println(messageObject);
        channel.basicAck((long) headers.get(AmqpHeaders.DELIVERY_TAG), false);
    }
}
